package com.topscomm.gpm.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.topscomm.gpm.pojo.GpmProjectEntity;
import com.topscomm.gpm.pojo.GpmProjectMilepostEntity;
import com.topscomm.gpm.pojo.GpmProjectTaskEntity;
import com.topscomm.gpm.service.IGpmProjectMilepostService;
import com.topscomm.gpm.service.IGpmProjectService;
import com.topscomm.gpm.service.IGpmProjectTaskService;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.vo.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

/**
 * @author liwanpeng
 * @version 1.0
 * @description: TODO
 * @date 2021/1/23 14:32
 */
@Service
public class GpmGanttService {
    @Autowired
    private IGpmProjectService gpmProjectService;
    @Autowired
    private IGpmProjectMilepostService gpmProjectMilepostService;
    @Autowired
    private IGpmProjectTaskService gpmProjectTaskService;
    /**
     * @description: 获取甘特图信息
     * @param: projectId
     * @return: com.topscomm.pub.vo.ResponseResult<java.lang.Object>
     * @author Administrator
     * @date: 2021/1/23 14:34
     */
    public ResponseResult<Object> getGanttInfo(long projectId){
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> resultForData = new ArrayList<>();
        List<Map<String, Object>> resultForLink = new ArrayList<>();
        // 获取项目信息
        GpmProjectEntity gpmProjectEntity = gpmProjectService.queryById(String.valueOf(projectId));
        // 转换为甘特图需要的数据格式
        Map<String, Object> projectGantInfo =  new HashMap<>();
        projectGantInfo.put("id",projectId+"P");
        projectGantInfo.put("text", gpmProjectEntity.getProjectname());
        // 计算进度：（当前时间-计划开始）/（计划结束-计划开始）
        DecimalFormat df=new DecimalFormat("0.0000"); // 设置保留位数
        long planDay = DateUtil.betweenDay(gpmProjectEntity.getPlanstartdate(), DateUtil.offsetDay(gpmProjectEntity.getPlanenddate(),1), false);
        long actualDay = DateUtil.betweenDay(gpmProjectEntity.getPlanstartdate(), new Date(), false);
        projectGantInfo.put("duration",planDay);
        projectGantInfo.put("progress",df.format((float)actualDay/planDay));
        projectGantInfo.put("open",true);
        projectGantInfo.put("type","sdProject");
        projectGantInfo.put("abnormalState", gpmProjectEntity.getAbnormalstate());
        projectGantInfo.put("start_date", DateUtil.formatDate(gpmProjectEntity.getPlanstartdate()));
        projectGantInfo.put("plan_end_date",DateUtil.formatDate(gpmProjectEntity.getPlanenddate()));
        projectGantInfo.put("end_date",DateUtil.formatDate(DateUtil.offsetDay(gpmProjectEntity.getPlanenddate(),1)));
        resultForData.add(projectGantInfo);
        // 获取里程碑信息
        StringBufferProxy whereSql = new StringBufferProxy();
        whereSql.appendSingle(" projectcode = '{0}' and enabled = 1 order by planfinishtime asc,id asc ", gpmProjectEntity.getProjectcode());
        List<GpmProjectMilepostEntity> sdProjectMilepostEntities = gpmProjectMilepostService.queryByWhere(whereSql.toString());
        // 转换为甘特图需要的数据格式
        sdProjectMilepostEntities.forEach(item->{
            Map<String, Object> milepostGantt =  new HashMap<>();// 甘特图信息

            milepostGantt.put("id",item.getOperatecode()+"M");
            milepostGantt.put("text",item.getMilepostname());
            milepostGantt.put("parent",projectId+"P");
            if (ObjectUtil.isEmpty(item.getActualfinishtime())){
                milepostGantt.put("plan_start_date", DateUtil.formatDate(DateUtil.offsetDay(item.getPlanfinishtime(),0)));
                milepostGantt.put("start_date", DateUtil.formatDate(DateUtil.offsetDay(item.getPlanfinishtime(),0)));
            }else {
                milepostGantt.put("plan_start_date", DateUtil.formatDate(DateUtil.offsetDay(item.getPlanfinishtime(),0)));
                milepostGantt.put("start_date", DateUtil.formatDate(DateUtil.offsetDay(item.getActualfinishtime(),0)));
            }
            milepostGantt.put("type","milestone");
            // 判断是否超期
            if (new Date().getTime()>item.getPlanfinishtime().getTime()&&item.getEnabled()==1&&item.getMilepoststate()==0){
                milepostGantt.put("isOverdue",true);
            }else {
                milepostGantt.put("isOverdue",false);
            }
            Map<String, Object> lineMap =  new HashMap<>();// 连接线信息
            lineMap.put("id",item.getId()+"M");
            lineMap.put("source",projectId+"P");
            lineMap.put("target",item.getOperatecode()+"M");
            lineMap.put("type",1);
            resultForLink.add(lineMap);
            resultForData.add(milepostGantt);
        });
        // 获取任务信息
        whereSql.clear();
        whereSql.appendSingle(" projectcode = '{0}' and enabled = 1 and state = 9 order by planstartdate asc ", gpmProjectEntity.getProjectcode());
        List<GpmProjectTaskEntity> sdProjectTaskEntities = gpmProjectTaskService.queryByWhere(whereSql.toString());
        // 转换为甘特图需要的数据格式
        sdProjectTaskEntities.forEach(item->{
            Map<String, Object> taskGanttPlan =  new HashMap<>(); // 计划
            taskGanttPlan.put("id",item.getId()+"T");
            taskGanttPlan.put("text",item.getTaskname());
            taskGanttPlan.put("parent",item.getMilepostcode()+"M");
            taskGanttPlan.put("plan_start_date",DateUtil.formatDate(item.getPlanstartdate()));// 计划开始时间
            // 实际开始时间（如果任务未开始则使用计划开始时间，且将任务状态置为未开始）
            if ("0".equals(item.getTaskstate())){
                taskGanttPlan.put("start_date", DateUtil.formatDate(item.getPlanstartdate()));// 使用计划开始时间
            }else {
                // 使用实际开始时间
                taskGanttPlan.put("start_date", DateUtil.formatDate(item.getActualstartdate()));// 使用计划开始时间
            }
            taskGanttPlan.put("task_state",item.getTaskstate()); // 任务状态
            // 如果任务已结束，使用实际结束时间，否则使用计划结束时间
            taskGanttPlan.put("plan_end_date", DateUtil.formatDate(DateUtil.offsetDay(item.getPlanenddate(),0)));// 使用计划结束时间
            if ("2".equals(item.getTaskstate())&&item.getActualenddate()!=null){
                taskGanttPlan.put("end_date", DateUtil.formatDate(DateUtil.offsetDay(item.getActualenddate(),1)));// 使用实际结束时间
            }else {
                taskGanttPlan.put("end_date", DateUtil.formatDate(DateUtil.offsetDay(item.getPlanenddate(),1)));// 使用计划结束时间
            }
            taskGanttPlan.put("task_state",item.getTaskstate()); // 任务状态
            // 判断是否超期（任务未完成，且计划完成时间小于当前时间；任务已完成，且计划完成时间小于实际完成时间）
            boolean isfinished = (item.getTaskstate().equals("2"));
            if (new Date().getTime() > item.getPlanenddate().getTime() && !isfinished){
                taskGanttPlan.put("isOverdue",true);
            } else if (isfinished && item.getActualenddate().getTime() > item.getPlanenddate().getTime()) {
                taskGanttPlan.put("isOverdue",true);
            } else {
                taskGanttPlan.put("isOverdue",false);
            }
            taskGanttPlan.put("progress",ConvertUtil.convertToBigDecimal(item.getTaskschedule()).divide(new BigDecimal(100)).floatValue());
            taskGanttPlan.put("type","sdTask");
            Map<String, Object> lineMap =  new HashMap<>();// 连接线信息
            lineMap.put("id",item.getId()+"");
            lineMap.put("source",item.getId()+"T");
            lineMap.put("target",item.getMilepostcode()+"M");
            lineMap.put("type",0);
//            resultForLink.add(lineMap);
            resultForData.add(taskGanttPlan);
        });
        result.put("data",resultForData);
        result.put("links",resultForLink);
        return ResponseResult.ok(result);
    }
}
